﻿@inherits JSModuleComponentBase
@attribute [JSModuleAutoLoader("topology", ModuleName = "Topology", JSObjectReference = true)]
@inject FanControllerDataService DataService
@inject SwalService SwalService

<Button OnClickWithoutRender="OnResize" Text="Resize" />

<div class="topology mt-3">
    <Topology @ref="TopologyElement" Content="@Content" OnBeforePushData="OnBeforePushData"></Topology>
</div>

@code {
    private string? Content { get; set; }

    [NotNull]
    private Topology? TopologyElement { get; set; }

    private JSInterop<TopologiesNomal>? Interop { get; set; }

    private Task OnResize()
    {
        TopologyElement.Resize();
        return Task.CompletedTask;
    }

    /// <summary>
    /// <inheritdoc/>
    /// </summary>
    protected override void OnInitialized()
    {
        base.OnInitialized();
        var assembly = typeof(TopologiesNomal).Assembly;
        var strName = assembly.GetName().Name + ".topology.json";
        var stream = assembly.GetManifestResourceStream(strName);
        if (stream != null)
        {
            using var reader = new StreamReader(stream);
            Content = reader.ReadToEnd();
        }
    }

    /// <summary>
    /// <inheritdoc/>
    /// </summary>
    /// <returns></returns>
    protected override Task ModuleInitAsync() => InvokeInitAsync(TopologyElement.Id, nameof(ToggleFan));

    /// <summary>
    /// 切换风扇状态方法
    /// </summary>
    /// <param name="tagName"></param>
    /// <returns></returns>
    [JSInvokable]
    public async Task ToggleFan(string tagName)
    {
        var open = DataService.IsOpen;
        var op = new SwalOption()
            {
                Title = open ? "关闭风扇" : "打开风扇",
                Content = open ? "您确定要关闭风扇吗？" : "您确定要打开风扇吗？",
                Category = SwalCategory.Information
            };
        open = !open;
        var ret = await SwalService.ShowModal(op);
        if (ret)
        {
            await DataService.UpdateStatus(open);
        }
    }

    private async Task OnBeforePushData()
    {
        await InvokeExecuteAsync(TopologyElement.Id);

        // 推送数据
        var data = DataService.GetDatas();
        await TopologyElement.PushData(data);

        // 数据订阅
        DataService.OnDataChange = async datas => await TopologyElement.PushData(datas);
    }

    /// <summary>
    /// Dispose
    /// </summary>
    /// <param name="disposing"></param>
    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
        {
            if (Interop != null)
            {
                Interop.Dispose();
                Interop = null;
            }
        }
    }

    /// <summary>
    /// Dispose
    /// </summary>
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
}
